package com.zyt.wiki.controller;

import com.zyt.wiki.req.DocSaveReq;
import com.zyt.wiki.resp.CommonResp;
import com.zyt.wiki.resp.DocQueryResp;
import com.zyt.wiki.service.DocService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/doc")
public class DocController {

    public static final Logger LOG = LoggerFactory.getLogger(DocController.class) ;

    @Autowired
    private DocService docService ;

    // Get：http://localhost:8880/doc/all
    @GetMapping("/all/{ebookId}")
    public CommonResp all(@PathVariable Long ebookId){
        CommonResp<List<DocQueryResp>> resp = new CommonResp<>() ;
        List<DocQueryResp> list = this.docService.all(ebookId);
        resp.setContent(list);
        return resp ;
    }

    // 【POST提交时】注意：
    //      前端若是application/x-www-form-urlencoded表单提交，则参数前面不用@RequestBody也能正常映射到参数；
    //      若是application/json方式提交，则需要@RequestBody把参数接收进来
    // axios的post提交，是用application/json方式提交的，所以要加@RequestBody
    @PostMapping("/save")
    public CommonResp save(@Valid @RequestBody DocSaveReq req){
        CommonResp resp = new CommonResp() ;
        this.docService.save(req) ;
        return  resp ;
    }

    @DeleteMapping("/delete/{idsStr}")
    public CommonResp delete(@PathVariable String idsStr){
        CommonResp resp = new CommonResp() ;
        List<String> idList = Arrays.asList(idsStr.split(","));// 将idsStr按","分割成数组再转化为List
        this.docService.delete(idList) ;
        return resp ;
    }

    @GetMapping("/find-content/{id}")
    public CommonResp findContent(@PathVariable Long id){
        CommonResp resp = new CommonResp() ;
        String content = this.docService.findContent(id) ;
        resp.setContent(content);
        return resp ;
    }

    @GetMapping("/vote/{id}")
    public CommonResp vote(@PathVariable Long id){
        CommonResp resp = new CommonResp() ;
        this.docService.vote(id) ;
        return resp ;
    }

}
